#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie137@gmail.com)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.

__docformat__ = 'reStructuredText'

from item import Item
from tel_number import TelNumber
from str import Str
from contact import Contact, ContactsService, SelectContactService

from attribute import Attribute


class Peer(Item):

    def __init__(self, value='', **kargs):
        super(Peer, self).__init__(**kargs)
        self.value = value

    def __get_value(self):
        return self.__value

    def __set_value(self, value):
        if isinstance(value, (basestring, Str)):
            value = unicode(value)
            try:
                self.__value = TelNumber(value)
            except ValueError:
                self.__value = ContactsService.get().find_by_name(value)
        elif isinstance(value, Contact):
            self.__value = value
        elif isinstance(value, Peer):
            self.__value = value.value
        else:
            raise TypeError
        self.title = self.value.title

    value = property(__get_value, __set_value)

    def view(self, parent, **kargs):
        return self.title.view(parent, **kargs)

    def __get_tel(self):
        if isinstance(self.value, TelNumber):
            return self.value
        else:
            return self.value.tel

    def __set_tel(self, tel):
        self.value = TelNumber.as_type(tel)

    tel = property(__get_tel, __set_tel)

    def serialize(self):
        return unicode(self.value)

    @classmethod
    def unserialize(cls, data):
        return cls(value)

    def create_actor(self):
        actor = super(Peer, self).create_actor()

        def on_contact(actor, item):
            select_contact = SelectContactService.get()
            contact = yield select_contact.select()
            if not contact:
                yield None
            if not contact.tel:
                yield tichy.Dialog(None, "Error", "contact has no tel")
                yield None
            item.value = contact

        actor.new_action("Contact").connect('activated', on_contact)

        def on_edit(actor, item):
            tel = self.tel
            yield tel.edit()
            self.tel = tel

        actor.new_action("Edit").connect('activated', on_edit)

        return actor
